package cn.itcast.controller.system;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.system.Dept;
import cn.itcast.service.system.DeptService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/system/dept")
public class DeptController extends BaseController {


    @Autowired
    private DeptService deptService;

    @RequestMapping(value = "/list",name = "分页展示部门数据列表展示") // page代表当前的页码  page=2
    public String findAll(@RequestParam(value = "page",defaultValue = "1") Integer pageNum , @RequestParam(defaultValue = "10")Integer pageSize){

        PageInfo pageInfo = deptService.findPage(getCompanyId(),pageNum,pageSize);
        request.setAttribute("page",pageInfo); //这里的page名称不能改，因为页面要的就是page这个名称
        return "system/dept/dept-list";
    }

    @RequestMapping(value = "/toAdd",name = "跳转到新增部门页面")
    public String toAdd(){
//        查询本企业的所有部门
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList",deptList);

        return "system/dept/dept-add";
    }

    @RequestMapping(value = "/edit",name = "保存部门信息")
    public String edit(Dept dept){

        if(dept.getParent().getId().equals("")){
            dept.getParent().setId(null);
        }

        if(StringUtils.isNotEmpty(dept.getId())){
//           id不为空，应该执行修改方法
            deptService.update(dept);
        }else{
            dept.setId(UUID.randomUUID().toString());
            dept.setCompanyId(getCompanyId());
            dept.setCompanyName(getCompanyName());
            deptService.save(dept);
        }
        return "redirect:/system/dept/list.do"; // 重定向到列表页面
    }
    @RequestMapping(value = "/toUpdate",name = "跳转到修改部门页面")
    public String toUpdate(String id){
        Dept dept = deptService.findById(id);
        request.setAttribute("dept",dept);

        //        查询本企业的所有部门
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList",deptList);

//        新增和修改页面共用一个
        return "system/dept/dept-add";
    }
    @RequestMapping(value = "/delete",name = "删除部门数据")
    public String delete(String id){
        deptService.deleteById(id);
        return "redirect:/system/dept/list.do"; // 重定向到列表页面
    }
    @RequestMapping(value = "/deleteByIds",name = "删除部门数据")
    public String deleteByIds(String[] ids){

        for (String id : ids) {
            deptService.deleteById(id);
        }

        return "redirect:/system/dept/list.do"; // 重定向到列表页面
    }

}
